package com.liunian.algorithmstudy.tree;

public class LowestCommonAncestor235 extends TreeNode {

	public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
		if (root == null) {
			return null;
		} else if (p == root || q == root) {
			return root;
		}
		int maxVal = Math.max(p.val, q.val), minVal = Math.min(p.val, q.val);
		TreeNode leftTree = null;
		TreeNode rightTree = null;
		if (root.val > maxVal) {
			leftTree = lowestCommonAncestor1(root.left, p, q);
		} else if (root.val < minVal) {
			rightTree = lowestCommonAncestor1(root.right, p, q);
		} else {
			leftTree = lowestCommonAncestor1(root.left, p, q);
			rightTree = lowestCommonAncestor1(root.right, p, q);
		}
		if (leftTree != null && rightTree != null) {
			return root;
		} else if (leftTree == null && rightTree == null) {
			return null;
		} else if (leftTree != null) {
			return leftTree;
		} else {
			return rightTree;
		}
	}

	public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
		if(root == null) {
			return null;
		}
		if (root.val > Math.max(p.val, q.val)) {
			return lowestCommonAncestor2(root.left, p, q);
		}
		if (root.val < Math.min(p.val, q.val)) {
			return lowestCommonAncestor2(root.right, p, q);
		}
		return root;
	}

	public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		while (root != null) {
			if (root.val > Math.max(p.val, q.val)) {
				root = root.left;
			} else if (root.val < Math.min(p.val, q.val)) {
				root = root.right;
			} else {
				break;
			}
		}
		return root;
	}

}
